package com.twu.biblioteca;

import com.twu.biblioteca.command.Command;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: twer
 * Date: 5/25/13
 * Time: 12:45 AM
 * To change this template use File | Settings | File Templates.
 */
public class UsersManager {
    private static UsersManager usersManager;
    private static Map<String, User> users = new HashMap<String, User>();
    private User loginUser;
    private PrintWriter printWriter = new PrintWriter(System.out);
    private static InputStreamReader inputReader = new InputStreamReader(System.in);

    static {
        User user = new User("111-1111","1234");
        user.setEmail("test@test.com");
        user.setPhone("123456789");
        users.put(user.getUsername(), user);
    }

    private Set<Command> authenticationList = new HashSet<Command>();

    public User getLoginUser(){
        return loginUser;
    }

    public boolean login(String username, String password){
        User user = users.get(username);
        if(user == null) return false;
        if (!user.getPasswd().equals(password)) return false;
        loginUser = user;
        return true;
    }

    public void logout(){
        loginUser = null;
    }

    private UsersManager(){}
    public static UsersManager getUserManager(){
        if(usersManager == null)
            return new UsersManager();
        return usersManager;
    }

    public void setInputReader(InputStreamReader inputReader) {
        UsersManager.inputReader = inputReader;
    }

    public void addUser(User user){
        users.put(user.getUsername(), user);
    }

    public void setPrintWriter(PrintWriter pw){
        printWriter = pw;
    }

    public boolean requireLogin() {
        if(loginUser != null)
            return true;

        printWriter.println("please login");
        printWriter.flush();
        BufferedReader br = new BufferedReader(inputReader);
        try {
            printWriter.print("username: ");
            printWriter.flush();
            String username = br.readLine();
            printWriter.print("password: ");
            printWriter.flush();
            String password = br.readLine();
            return login(username, password);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return false;  //To change body of created methods use File | Settings | File Templates.
    }

    public void needAuthentication(Command command){
       authenticationList.add(command);
    }

    public boolean authenticate(Command commandObj) {
        if(authenticationList.contains(commandObj)){
            return requireLogin();
        }
        return true;
    }
}
